CREATE OR REPLACE FUNCTION business_Days_Between_Dates(start date, fim date) RETURNS integer AS $$
DECLARE
	i date;
	totalDays integer;
	holidaysInInterval integer;
BEGIN
	i := start;
	totalDays := 0;
	
	WHILE i <= fim LOOP
		IF extract(dow from i) not in (0, 6) then
			totalDays := totalDays + 1;
		end if;
		i := i + interval '1 day';
	END LOOP;

	SELECT COUNT(DISTINCT holidayDate) INTO holidaysInInterval
				FROM holiday
				WHERE holidayDate >= start AND holidayDate <= fim;

	RETURN totalDays - holidaysInInterval;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION business_Days_Since_Date(start date) RETURNS integer AS $$
BEGIN
	IF start > date(now()) THEN
		RETURN 0;
	ELSE
		RETURN business_Days_Between_Dates(start, date(now() - interval '1 day'));
	END IF;
END;
$$ LANGUAGE plpgsql; 

CREATE OR REPLACE FUNCTION is_Business_Day (DAY DATE) RETURNS BOOLEAN AS $$
BEGIN
	RETURN (EXTRACT(DOW FROM DAY) NOT IN (0, 6)) AND
				(0 = (SELECT COUNT(*) FROM HOLIDAY WHERE HOLIDAYDATE = DAY));
END;
$$ LANGUAGE plpgsql

